﻿@page "/login"
@layout NullLayout
@using System.IdentityModel.Tokens.Jwt;
@using AdminShared.Models.Authorize
@attribute [ReuseTabsPage(Ignore = true)]


<body>
    <div style="width: 100vw;height: 100vh;text-align: center;background-image: url('img/bg.svg');">
        <div style="min-width: 360px;display: inline-block;padding-top: calc(50vh - 170px);">
            <h1>管理系统登录</h1>

            <Form Model="@loginData" OnFinish="OnFinish">

                <FormItem>
                    <Input @bind-Value="@context.Name" Placeholder="用户名" />
                </FormItem>

                <FormItem>
                    <InputPassword @bind-Value="@context.PassWord" Placeholder="密码" />
                </FormItem>

                <FormItem>
                    <Button Type="@ButtonType.Primary" HtmlType="submit" Block Loading="@loginLoading">
                        登录
                    </Button>
                </FormItem>
            </Form>

        </div>
    </div>
</body>


@code
{
    bool loginLoading = false;


    override protected void OnInitialized()
    {
        var authorization = LocalStorage.GetItemAsString("Authorization");

        if (!string.IsNullOrEmpty(authorization))
        {
            JwtSecurityToken securityToken = new(authorization);

            var expTimeL = Convert.ToInt64(securityToken.Claims.ToList().Where(t => t.Type == "exp").FirstOrDefault()!.Value);

            var expTime = TimeZoneInfo.ConvertTimeToUtc((new DateTime(1970, 1, 1)).ToLocalTime()).ToLocalTime().AddSeconds(expTimeL);

            if (expTime > DateTime.UtcNow)
            {
                NavigationManager.NavigateTo("");
            }
        }
    }


    private DtoLogin loginData = new();

    private async void OnFinish()
    {

        loginLoading = true;

        using (var httpResponse = await Http.PostAsJsonAsync<DtoLogin>("Authorize/GetToken", loginData))
        {
            if ((int)httpResponse.StatusCode == 200)
            {
                var token = httpResponse.Content.ReadAsStringAsync().Result;
                LocalStorage.SetItemAsString("Authorization", token);
                NavigationManager.NavigateTo("");
            }
        }

        loginLoading = false;

        StateHasChanged();

    }

}